import { protectedProcedure, router } from '@/server/trpc-middlewares/trpc';
import { createAppSchema } from '../db/validate-schema';
import { v4 as uuid } from 'uuid';
import { db } from '../db/db';
import { apps, storageConfiguration } from '../db/schema';
import { and, desc, eq } from 'drizzle-orm';
import { z } from 'zod';
import { TRPCError } from '@trpc/server';

export const appsRouter = router({
  createApp: protectedProcedure
    .input(createAppSchema.pick({ name: true, description: true }))
    .mutation(async ({ ctx, input }) => {
      const [newApp] = await db
        .insert(apps)
        .values({
          id: uuid(),
          name: input.name,
          description: input.description,
          userId: ctx.session.user.id,
        })
        .returning();

      return newApp;
    }),

  listApps: protectedProcedure.query(async ({ ctx }) => {
    const userApps = await db.query.apps.findMany({
      where: (apps, { eq, and, isNull }) =>
        and(eq(apps.userId, ctx.session.user.id), isNull(apps.deletedAt)),
      orderBy: [desc(apps.createdAt)],
    });
    return userApps;
  }),

  changeStorage: protectedProcedure
    .input(
      z.object({
        appId: z.string(),
        storageId: z.number(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      const storage = await db.query.storageConfiguration.findFirst({
        where: (storage, { eq, and }) =>
          and(
            eq(storage.userId, ctx.session.user.id),
            eq(storage.id, input.storageId)
          ),
      });

      if (!storage) {
        throw new TRPCError({
          code: 'FORBIDDEN',
        });
      }

      await db
        .update(apps)
        .set({
          storageId: input.storageId,
        })
        .where(
          and(eq(apps.id, input.appId), eq(apps.userId, ctx.session.user.id))
        );
    }),
});
